package com.android.task5;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;

public class GPSService extends Service implements LocationListener {

	private callBackService activity;
	LocationManager locationManager;
	LocationListener locationListener;
	
	double latitude;
	double longitude;
	
	boolean isLocationUpdatesActivated = false;
	
	public void onCreate(){
		super.onCreate();
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
		locationListener = this;
	}
	
	@Override
	public void onLocationChanged(Location loc) {
		// TODO Auto-generated method stub
		
		double latTMP = loc.getLatitude();
		double longTMP = loc.getLongitude();
		
		if(latTMP != latitude && longTMP !=longitude){
			latitude = latTMP;
			longitude = longTMP;
			try {
				if(activity != null)
					activity.updateLocation(latitude, longitude);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return iBinder;
	}
	
	public final service.Stub iBinder = new service.Stub(){

		@Override
		public boolean toogleGPSOnOff() throws RemoteException {
			if(isLocationUpdatesActivated){
				locationManager.removeUpdates(locationListener);
				isLocationUpdatesActivated = false;
			}
			else{
				locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
				isLocationUpdatesActivated = true;
			}
			return isLocationUpdatesActivated;
		}

		@Override
		public void setCallBack(IBinder iBinder) throws RemoteException {
			
			activity = callBackService.Stub.asInterface(iBinder);
//			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
			isLocationUpdatesActivated = false;
		}

		@Override
		public void sleepService() throws RemoteException {
			if(isLocationUpdatesActivated){
				locationManager.removeUpdates(locationListener);
				isLocationUpdatesActivated = false;
			}
		}

		@Override
		public void wakeUpService() throws RemoteException {
			if(!isLocationUpdatesActivated){
				locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
				isLocationUpdatesActivated = true;
			}
		}
		
	};
	

}
